package org.example.chinesedays.utils;

import org.example.chinesedays.entity.dto.DateRangeDTO;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class HolidayParser {
    public static List<DateRangeDTO> parseHolidays(String txt) {
        List<DateRangeDTO> result = new ArrayList<>();
        int year = extractYear(txt);
        for (String s : extractFestivalParagraphs(txt)) {
            DateRangeDTO dateRange = parseHolidayRange(s, year);
            if (dateRange != null) result.add(dateRange);
        }
        return result;
    }
    // 解析单个节日的放假范围
    public static DateRangeDTO parseHolidayRange(String txt, int year) {
        Matcher m = Pattern.compile("：(.*?)放假").matcher(txt);
        if (!m.find()) return null;
        String name = txt.split("、")[1].split("：")[0];
        String dateRange = m.group(1).trim();
        String[] parts = dateRange.split("至");
        LocalDate start = parseDate(parts[0].trim(), year);
        LocalDate end = parts.length > 1 ? parseEndDate(parts[1].trim(), start.getMonthValue(), year) : start;
        return new DateRangeDTO(start,end,name);
    }
    public static int extractYear(String txt) {
        Matcher m = Pattern.compile("关于(\\d{4})年").matcher(txt);
        if (m.find()) {
            return Integer.parseInt(m.group(1));
        }
        throw new IllegalArgumentException("无法从txt中解析年份");
    }

    public static List<DateRangeDTO> parseAdjustedWorkdays(String txt){
        List<DateRangeDTO> dateRanges = new ArrayList<>();
        for (String paragraph : extractFestivalParagraphs(txt)) {
            dateRanges.addAll(parseAdjustedDays(paragraph, extractYear(txt)));
        }
        return dateRanges;
    }

    // 提取所有节日段落（格式："一、节日名称："）
    private static List<String> extractFestivalParagraphs(String txt) {
        List<String> paragraphs = new ArrayList<>();
        String[] split = txt.split("\\r?\\n");
        for (String line : split) {
            if (line.matches("^[一二三四五六七八九十]、.*")) {
                paragraphs.add(line);
            }
        }
        return paragraphs;
    }
    // 解析调休工作日
    public static List<DateRangeDTO> parseAdjustedDays(String text, int year){
        List<DateRangeDTO> days = new ArrayList<>();
        String name = text.split("、")[1].split("：")[0]+"补班";
        for (String sentence : text.split("。")) {
            if (sentence.contains("上班")) {
                Matcher m = Pattern.compile("(\\d{1,2})月(\\d{1,2})日").matcher(sentence);
                while (m.find()) {
                    try {
                        LocalDate localDate = LocalDate.of(year,
                                Integer.parseInt(m.group(1)),
                                Integer.parseInt(m.group(2)));

                        days.add(new DateRangeDTO().setStart(localDate)
                                .setName(name));
                    } catch (Exception e) {
                        System.err.println("调休日期解析失败: " + m.group());
                    }
                }
            }
        }
        return days;
    }
    // 修改日期解析方法
    private static LocalDate parseDate(String dateStr, int year) {
        Matcher m = Pattern.compile("(\\d{1,2})月(\\d{1,2})日").matcher(dateStr);
        if (m.find()) {
            return LocalDate.of(year, // 使用动态年份
                    Integer.parseInt(m.group(1)),
                    Integer.parseInt(m.group(2)));
        }
        throw new IllegalArgumentException("无效日期格式: " + dateStr);
    }

    // 解析结束日期（可能省略月份）
    private static LocalDate parseEndDate(String dateStr, int baseMonth, int year) {
        try {
            return parseDate(dateStr, year);
        } catch (IllegalArgumentException e) {
            // 尝试解析省略月份的情况（如"6日"）
            Matcher m = Pattern.compile("(\\d{1,2})日").matcher(dateStr);
            if (m.find()) {
                return LocalDate.of(year, baseMonth,
                        Integer.parseInt(m.group(1)));
            }
            throw new IllegalArgumentException("无效结束日期: " + dateStr);
        }
    }
}